package cn.edu.pzhu.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.pzhu.pojo.Msg;
import cn.edu.pzhu.pojo.User;
import cn.edu.pzhu.service.UserService;
import cn.edu.pzhu.service.imp.UserServiceImp;
import cn.edu.pzhu.util.Conver2MD5;

/**
 * Servlet implementation class UpdataPasswordServlet
 */
@WebServlet("/UpdatePassword")
public class UpdatePasswordServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdatePasswordServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
				//1.接收参数
				String username=request.getParameter("username");
				String password=request.getParameter("password");
				
				HttpSession session =  request.getSession();
				
				//2.数据校验
				//检查密码不能为空
				if("".equals(password)) { 
					//提醒密码不能为空			
					session.setAttribute("msg", "密码栏不能为空");
					session.setAttribute("url", "userinfo.jsp");
					//返回视图View(异常处理建议使用重定向)
					response.sendRedirect("error.jsp");
					return; //流程结束，后续代码不需要再执行...
				}
				//检查密码不能低于6位
				if(password.length() < 6 ) { 
					//提醒密码不能为空			
					session.setAttribute("msg", "密码长度不符合要求，不能少于6位！");
					session.setAttribute("url", "userinfo.jsp");
					//返回视图View(异常处理建议使用重定向)
					response.sendRedirect("error.jsp");
					return; //流程结束，后续代码不需要再执行...
				}
			
				String md5password = Conver2MD5.getSHA256(Conver2MD5.getSHA256(username+password)+"pzhu");
				
				//3.数据封装
				User user = new User(username,md5password,1);//默认账号可用，状态为1	
				
				//4.调用模型
				UserService us = new UserServiceImp();
				
				Msg msg = us.update(user.getUsername(), user);     // 修改个人信息
				
				//5.保存信息回到视图
				if (msg.isSuccess()) {
					session.setAttribute("user", null);
				}

				//6.回到个人信息页面
				response.setContentType("text/html;charset=utf-8");
				response.getWriter().print("<script>alert('密码修改成功，请重新登录！');location.href='login.jsp'</script>");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
